package xmlexperiment;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/** A quick experiment using the Java XML package. I need to produce a stats engine.
 *  The engine would take an XML play as input, and return a representation of that
 *  play which would be useful to other multipart components. This includes a 
 *  summary of all characters plus the number of lines they speak in the play. The
 *  engine would require two arguments - path to file and name or target tag. 
 *
 * @author Mark Truran
 */
public class TextXML {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) 
    {
        ArrayList<Speech> al = null;

        
        try 
        {
            // Create a document object that represents the XML file
            String filepath = "all_well.xml";
            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
            Document doc = docBuilder.parse(filepath);
            
            // Not happy with this code - very inefficent? consider XPath solution.
            NodeList list = doc.getElementsByTagName("SPEECH");
            al = new ArrayList<Speech>();
            
            for(int i = 0; i < list.getLength(); i++)
            {
                Node fstNode = list.item(i);
    
                 if (fstNode.getNodeType() == Node.ELEMENT_NODE) 
                 {
                     Element fstElmnt = (Element) fstNode;
                     NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("SPEAKER");
                     String charName = fstNmElmntLst.item(0).getTextContent();
                     
                     fstNmElmntLst = fstElmnt.getElementsByTagName("LINE");
                     String[] lines = new String[fstNmElmntLst.getLength()];
                     for(int j = 0; j < fstNmElmntLst.getLength(); j++)
                     {
                         fstNode = fstNmElmntLst.item(j);
                         String s = fstNode.getTextContent();
                         lines[j] = s;
                     }
                     al.add(new Speech(charName, lines));
                 }
            }
 
	} catch (ParserConfigurationException pce) 
        {
		pce.printStackTrace();
	} catch (IOException ioe) 
        {
		ioe.printStackTrace();
	} catch (SAXException sae) 
        {
		sae.printStackTrace();
	}
    }
}
